package com.anuyun.ms.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * @author yufeng
 *
 */
public class Md5Util {
	
	private static final String MD5_ALGORITHM_NAME = "MD5";
	
	private static final char[] HEX_CHARS =
		{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
	
	public static String md5AsHex(String str) {
		MessageDigest md5Digest = getDigest();
		
		byte[] digest = md5Digest.digest(str.getBytes());
		
		char[] hexDigest = encodeHex(digest);
		
		return new String(hexDigest);
	}
	
	
	public static byte[] md5(String str) {
		MessageDigest md5Digest = getDigest();
		
		return md5Digest.digest(str.getBytes());
	}
	
	
	private static MessageDigest getDigest() {
		try {
			return MessageDigest.getInstance(MD5_ALGORITHM_NAME);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + MD5_ALGORITHM_NAME + "\"", e);
		}
		
	}
	
	
	private static char[] encodeHex(byte[] bytes) {
		char[] chars = new char[32];
		for (int i = 0; i < chars.length; i = i + 2) {
			byte b = bytes[i / 2];
			chars[i] = HEX_CHARS[(b >>> 0x4) & 0xf];
			chars[i + 1] = HEX_CHARS[b & 0xf];
		}
		return chars;
	}
	
}
